import {wx_login, hyh_showModal} from '@/utils/hyh_uni_utils.js'

const db = uniCloud.database()
const userDB = db.collection('dish-user')
export default {
	state: {
		userInfo: {},
		push_clientid: '',
		publicInfo: {},
	},
	getters: {
		
	},
	mutations: {
		setUserInfo(state, data) {
			state.userInfo = {...state.userInfo, ...data}
			uni.setStorageSync('userInfo', state.userInfo)
		},
		setPushClientid(state, data) {
			state.push_clientid = data
		},
		setPublicInfo(state, data) {
			state.publicInfo = data
		},
	},
	actions: {
		async veriftUserInfo({state}) {
			const mapVerifyUser = {
				sex: '性别',
				phone: '手机号',
			}
			const verifyRes = Object.keys(mapVerifyUser).filter(k => !state.userInfo[k])
			if (verifyRes.length) {
				const flag = await hyh_showModal({
					title: '提示',
					content: `你还有${verifyRes.map(k => mapVerifyUser[k]).join(', ')}没有完善, 请先完善再选餐`,
					confirmText: '去完善'
				})
				if (flag) {
					await uni.switchTab({url:'/pages/profile/profile'})
				}
				return false
			}
			return true
		},
		async initUserInfo({commit, state, dispatch}) {
			const userInfo = uni.getStorageSync('userInfo')
			userInfo && commit('setUserInfo', userInfo)
			const {openid} = userInfo
			if (openid) {
				await dispatch('getUserInfo')
			} else {
				await dispatch('loginAction')
			}
			await dispatch('requestPublicInfo')
			uni.$emit('initUserInfo_end')
		},
		async loginAction({commit, state, dispatch}) {
			const wxCode = await wx_login({provider: 'weixin'}).then(r => r.code)
			const res = await uniCloud.callFunction({ 
				name: 'dish-user-create', 
				data: {wxCode} ,
			})
			commit('setUserInfo', {openid: res.result.openid})
			await dispatch('getUserInfo')
		},
		async getUserInfo({commit, state, dispatch}) {
			const openid = state.userInfo.openid
			await dispatch('veriftPhone')
			const user = userDB.where({openid}).getTemp()
			const res = await db.collection(user, 'dish-role').get()
			const data = res.result.data
			if (data.length) {
				commit('setUserInfo', data[0])
			} else {
				await dispatch('loginAction')
			}
		},
		async updateUserInfo({state, commit}, updateInfo) {
			try{
				const openid = state.userInfo.openid
				await userDB.where({openid}).update(updateInfo)
				commit('setUserInfo', updateInfo)
			}catch(e){
				//TODO handle the exception
				console.log(e);
			}
		},
		async veriftPhone({state, commit, dispatch}) {
			const phone = state.userInfo.phone
			if (phone) {
				const res = await db.collection('dish-phone').where({phone}).get()
				const role = res.result.data.length ? 'leader' : 'staff'
				await dispatch('updateUserInfo', {role})
			}
		},
		async requestPublicInfo({state, commit}) {
			const res = await db.collection('control-panel').get()
			const publicInfo = res.result.data[0]
			commit('setPublicInfo', publicInfo)
		}
	}
}
